import {
  login,
  logout,
  getInfo
} from '@/api/user'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'
import {
  resetRouter
} from '@/router'
import axios from 'axios'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: localStorage.getItem("avatar"),
    rules: [], //控制菜单显示
    loginLater: '',
    roles: [],
    progress: 0,//进度条
    cancelRequest: null,
    avTime: 0,  //可用音视频时长
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_RULES: (state, rules) => {
    state.rules = rules
  },
  LOGIN_LATER: (state, rules) => {
    state.loginLater = rules
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_PROGRESS: (state, progress) => {
    state.progress = progress
  },
  SET_CANCEL: (state, fun) => {
    state.cancelRequest = fun
  },
  SET_AV_TIME: (state, avTime) => {
    state.avTime = avTime
  }
}

const actions = {
  // user login
  login({
    commit
  }, userInfo) {
    const {
      username,
      password
    } = userInfo
    let data = {
      username: username.trim(),
      password: password,
      last_ip: sessionStorage.getItem("Ip")
    }
    return new Promise((resolve, reject) => {
      //设置请求头 userId 为空
      axios.post(`${process.env.VUE_APP_BASE_API}api/loginAdmin`, data).then(response => {
        const {
          data
        } = response
        if (data.code == 200) {
          let res = data.data
          commit('SET_TOKEN', res.token)
          setToken(res.token)
          localStorage.setItem('avatar', res.avatar == null ? JSON.stringify(res.avatar) : res.avatar)
          commit('SET_AVATAR', res.avatar == null ? JSON.stringify(res.avatar) : res.avatar)
          localStorage.setItem('username', res.username)
          localStorage.setItem('ID', res.id)
          localStorage.setItem('VIP', res.name)
          localStorage.setItem('roleName', res.title)
          localStorage.setItem('auth_group_id', res.auth_group_id)
          commit('SET_ROLES', [res.title])
          commit('SET_AV_TIME', res.av_time)
          resolve()
        } else {
          reject(data)
        }
      }).catch(error => {
        console.log('登录失败', error)
        reject(error)
      })
      // login(qs.stringify(data)).then(response => {
      //   const { data } = response
      //   commit('SET_TOKEN', data.id)
      //   setToken(data.id)
      //   localStorage.setItem('avatar',data.avatar)
      //   commit('SET_AVATAR',data.avatar)
      //   localStorage.setItem('username',data.username)
      //   localStorage.setItem('ID',data.id)
      //   localStorage.setItem('VIP',data.name)
      //   localStorage.setItem('roleName',data.title)
      //   localStorage.setItem('auth_group_id',data.auth_group_id)
      //   commit('SET_ROLES', [data.title])
      //   resolve()
      // }).catch(error => {
      //   console.log('请求失败',error)
      //   reject(error)
      // })
    })
  },

  // get user info
  getInfo({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const {
          data
        } = response
        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        const {
          name,
          avatar
        } = data
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({
    commit,
    state,
    dispatch
  }) {
    let data = {
      userId: localStorage.getItem("ID"),
      last_ip: sessionStorage.getItem("Ip")
    }
    return new Promise((resolve, reject) => {
      logout(data).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        var storage = window.localStorage;
        storage.clear()
        commit('RESET_STATE')
        dispatch('tagsView/delAllViews', null, { root: true })//退出登录删除所有菜单
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({
    commit
  }) {
    return new Promise(resolve => {
      removeToken() //必须先删除令牌
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
